import { stringify } from "querystring";
import { login, Logout, getUserInfo } from "../../api/user";
import { getToken, setToken, removeToken, getuserInfo } from '../../utils/auth'
const state = {
	userInfo: {},
	token: getToken(),
}

const mutations = {
	SET_TOKEN: (state: any, token: string) => {
		state.token = token
	},
	SET_USERINFO: (state: any, userInfo: object) => {
		state.userInfo = userInfo
	},

}

const actions = {
	login({ commit }: any, data: { userName: string, password: string }) {//用户登陆
		return new Promise((resolve, reject) => {
			login(data).then(res => {
				const { token } = res
				commit('SET_TOKEN', token)
				setToken(token)
				resolve(res)
			}).catch(err => {
				reject(err)
			})
		})
	},

	getInfo({ commit }: any, token: string) {//获取个人信息,菜单、元素权限
		return new Promise((resolve, reject) => {
			getUserInfo(token).then(res => {
				const obj = res;
				commit('SET_USERINFO', obj)
				resolve(obj)
			}).catch(err => {
				reject(err)
			})
		})
	},

	logOut({ commit }: any) {//用户退出
		return new Promise((resolve, reject) => {
			Logout().then(() => {
				commit('SET_TOKEN', '')
				commit('SET_USERINFO', {})
				removeToken()
				location.reload()
				resolve()
			}).catch(err => {
				reject(err)
			})
		})
	},

	resetToken({ commit }: any) {//删除token,用户token过期
		new Promise((resolve) => {
			commit('SET_TOKEN', '')
			commit('SET_USERINFO', {})
			removeToken()
			resolve()
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}